# -*- coding: utf8 -*-
# @Author   : lan_yue_chuan
# @time     : 2020/5/26 15:29
# @File     : myserializer.py
from rest_framework.serializers import Serializer,ModelSerializer
from app01.models import Goods, People, UserInfo
from rest_framework import serializers

class UserinfoSerializer(ModelSerializer):
    class Meta:
        model = UserInfo
        fields = "__all__"


class PeopleSerializer(ModelSerializer):
    user = UserinfoSerializer()
    class Meta:
        model = People
        fields = "__all__"


class GoodsSerializer(ModelSerializer):
    people = PeopleSerializer()
    # 覆盖hobby字段，显示出详情
    hobby = serializers.SerializerMethodField()
    class Meta:
        model = Goods
        fields = "__all__"

    def get_hobby(self,obj):
        return obj.get_hobby_display()

    # TODO:对单个字段验证，这是钩子函数，就跟form组件的钩子是一样的
    def validate_name(self, value):
        if "python" in value.lower():
            return value
        raise serializers.ValidationError('输入的商品名称必须包含python')

